package com.tamakloe.guestbook;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import com.google.appengine.api.urlfetch.*;

public class RecaptchaResponse {
    private static final String API_SSL_SERVER  ="https://api-secure.recaptcha.net";
    private static final String API_SERVER      ="http://api.recaptcha.net";
    private static final String VERIFY_SERVER   ="api-verify.recaptcha.net";
    private String errorCode;
    private boolean isValid;
  
    public RecaptchaResponse(boolean isValid, String errorCode){
        this.errorCode = errorCode;
        this.isValid = isValid;
    }
  
    public void setErrorCode(String errorCode){
        this.errorCode = errorCode;
    }
    public void setIsValid(boolean isValid){
        this.isValid = isValid;
    }
  
    public String getErrorCode(){
        return this.errorCode;
    }
    public boolean getIsValid(){
        return this.isValid;
    }
    /*
     *Gets the HTML to display for reCAPTCHA
     *publicKey -- The public api key
     *useSSL -- Should the request be sent over ssl?
     *error -- An error message to display (from RecaptchaResponse.error_code)"""
     */
    public String displayHtml(String publicKey, boolean useSSL, String error){
        String errorParam;
        String server;
        StringBuffer returnString = new StringBuffer();
      
        if (error != null){
            errorParam =  "&error=" + error;
        }else{
            errorParam = "";
        }
        if (useSSL){
            server = API_SSL_SERVER;
        } else {
            server = API_SERVER;
        }
        returnString.append("<script type=" + addQuote() + "text/javascript" + addQuote() + " src=" + addQuote() + server + "/challenge?k=" + publicKey + errorParam + addQuote() + "></script>" + "\n");
        returnString.append("<noscript>" + "\n");
        returnString.append("<iframe src=" + addQuote() + server + "/noscript?k=" + publicKey + errorParam + addQuote() + " height=" + addQuote() + "300" + addQuote() + " width=" + addQuote() + "500" + addQuote() +  "frameborder=" + addQuote() + "0" + addQuote() + "></iframe><br>" + "\n");
        returnString.append("<textarea name=" + addQuote() + "recaptcha_challenge_field" + addQuote() + " rows=" + addQuote() + "3" + addQuote() + " cols=" + addQuote() + "40" + addQuote() + "></textarea>" + "\n");
        returnString.append("<input type=" + addQuote() + "hidden" + addQuote() + " name=" + addQuote() + "recaptcha_response_field" + addQuote() + " value=" + addQuote() + "manual_challenge" + addQuote() + " />" + "\n");
        returnString.append("</noscript>");
        return returnString.toString();
    }
    public String addQuote(){
    	return "\"";
    }
    /*
     *Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
     *for the request
     *
     *recaptchaChallengeField -- The value of recaptcha_challenge_field from the form
     *recaptchaResponseRield -- The value of recaptcha_response_field from the form
     *privateKey -- your reCAPTCHA private key
     *remoteIp -- the user's IP address
     */
    public RecaptchaResponse submit(String recaptchaChallengeField, String recaptchaResponseField,
            String privateKey, String remoteIp){
    	RecaptchaResponse reCaptchaResp = new RecaptchaResponse(false, "recaptcha-submit-faild");
        if (recaptchaChallengeField == null & recaptchaResponseField == null){
            if (recaptchaChallengeField.length()==0 && recaptchaResponseField.length()==0){
            	reCaptchaResp.setIsValid(false);
            	reCaptchaResp.setErrorCode("incorrect-captcha-sol");
                return reCaptchaResp;
            }
        }

        //create header objects
        HTTPHeader headerContentType = new HTTPHeader("Content-type" , "application/x-www-form-urlencoded");
        HTTPHeader headerUserAgent = new HTTPHeader("User-agent" , "reCAPTCHA GAE Java");

        //build up pay load parameters
        String params = "";
		try {
			params = URLEncoder.encode ("privatekey", "UTF-8") + "=" + URLEncoder.encode(privateKey, "UTF-8") + "&"
			+ URLEncoder.encode ("remoteip", "UTF-8") + "=" + URLEncoder.encode(remoteIp,"UTF-8") + "&"
			+ URLEncoder.encode ("challenge", "UTF-8") + "=" + URLEncoder.encode(recaptchaChallengeField, "UTF-8") + "&"
			+ URLEncoder.encode ("response", "UTF-8") + "=" + URLEncoder.encode(recaptchaResponseField, "UTF-8");


	        //create URL object
	        URL dataURL = new URL("http://" + VERIFY_SERVER + "/verify");
	
	        //Create request object
	        HTTPRequest fetchreq = new HTTPRequest(dataURL, HTTPMethod.POST);
	        
	        //Add pay load and header
	        fetchreq.setPayload(params.getBytes("UTF-8"));
	        fetchreq.addHeader(headerContentType);
	        fetchreq.addHeader(headerUserAgent);
	        
	        //Get response
	        URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
	        HTTPResponse httpresp = fetcher.fetch(fetchreq);
	        if (httpresp.getResponseCode() == 200){
	            // response was fine
	            // get the return values
	            String[] returnValues = httpresp.getContent().toString().split("\r\n"); //.content.split lines();
	           
	            // get the return code (true/false)
	            String returnCode = returnValues[0];
	           
	            if (returnCode == "true"){
	                // yes, filled perfectly
	            	reCaptchaResp.setIsValid(true);
	            	reCaptchaResp.setErrorCode("");
	                return reCaptchaResp;	            	
	            } else {
	                // nope, something went wrong
	            	reCaptchaResp.setIsValid(false);
	            	reCaptchaResp.setErrorCode(returnValues[1].toString());
	                return reCaptchaResp;	            	
	            }
	        } else {
	            // recaptcha server was not reachable
            	reCaptchaResp.setIsValid(false);
            	reCaptchaResp.setErrorCode("recaptcha-not-reachable");
                return reCaptchaResp;	      	
	        }			
      
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return reCaptchaResp;
		
   }
  
}
